<?php

/**
 * WebNews class
 *
 * @author Julot
 * @since Thursday, June 9, 2011. 04:01 PM
 */
class WebNews extends News {

	public $type = News::TYPE_WEB;
//	public $recaptcha;
	public $verifyCode;

	static function model($className=__CLASS__) {
		return parent::model($className);
	}

	function defaultScope() {
		return array(
			'condition'=>"type='" . News::TYPE_WEB . "'",
		);
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		$allowEmpty = Yii::app()->params['mode'] == 'test' ||
			!CCaptcha::checkRequirements();
		$rules = array(
			array('sender, contact, value', 'required'),
			array('dateTime, sticky, hidden', 'numerical', 'integerOnly'=>true),
			array('sender, contact', 'length', 'max'=>255),
			array(
				'verifyCode',
				'captcha',
				'allowEmpty'=>$allowEmpty,
				'captchaAction'=>'news/captcha',
				'on'=>'insert',
			),
		);
		if (false && !(defined('YII_DEBUG') && YII_DEBUG)) {
			$rules[] = array(
				'recaptcha',
				'application.extensions.EReCaptchaValidator',
				'privateKey'=>Yii::app()->params['recaptcha']['key']['private'],
				'on'=>'insert',
			);
		}
		return $rules;
	}

	/**
	 * If new record, set notified, sticky and hidden to false.
	 * @see CActiveRecord beforeSave.
	 */
	protected function beforeSave() {
		if (!parent::beforeSave()) return false;

		if ($this->isNewRecord) {
			$this->dateTime = time();
			if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				$this->host = $_SERVER['HTTP_X_FORWARDED_FOR'];
			} elseif (isset($_SERVER['REMOTE_ADDR'])) {
				$this->host = $_SERVER['REMOTE_ADDR'];
			} else {
				$this->host = 'localhost';
			}
		}
		return true;
	}

	/**
	 * If logged and associated with member then set sender and contact.
	 * @see CActiveRecord beforeValidate.
	 */
	protected function beforeValidate() {
		if ($this->isNewRecord) {
			if (!Yii::app()->user->isGuest && Yii::app()->user->memberId) {
				// TODO: Get contact from member information
				$member = Member::model()->findByPk(Yii::app()->user->memberId);
				if ($member) {
					$this->sender = $member->name;
				}
			}
		}
		return parent::beforeValidate();
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		$labels = parent::attributeLabels();
		$labels['recaptcha'] = 'Masukkan kata-kata diatas';
		$labels['verifyCode'] = 'Masukkan kata diatas';
		return $labels;
	}

}
